package com.candy.security.jwt.filter;

import com.anji.captcha.model.common.ResponseModel;
import com.anji.captcha.model.vo.CaptchaVO;
import com.anji.captcha.service.CaptchaService;
import com.candy.common.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义用户名密码认证，要求必须要进行验证码认证
 * @author Lenovo
 */
public class CustomUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter
{
	private CaptchaService captchaService;

	public CustomUsernamePasswordAuthenticationFilter(CaptchaService captchaService)
	{
		this.captchaService = captchaService;
	}

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
	{
		try
		{
			String captchaVerification = ServletRequestUtils.getStringParameter(request, "captchaVerification");
			if(StringUtils.isEmpty(captchaVerification))
			{
				throw new BusinessException("未获取到验证码。");
			}
			CaptchaVO captchaVO = new CaptchaVO();
			captchaVO.setCaptchaVerification(captchaVerification);
			ResponseModel result = captchaService.verification(captchaVO);
			if(result.isSuccess() == false){
				throw new BusinessException("验证码错误。");
			}
		}
		catch (ServletRequestBindingException e)
		{
			e.printStackTrace();
			throw new BusinessException("验证码获取失败。"+e.getMessage());
		}
		return super.attemptAuthentication(request,response);
	}
}
